<?php

namespace app\api\controller;

use app\common\service\UsersService;
use think\Db;
use think\Exception;
use think\Request;

class User
{

    public function mobile_login()
    {
        $validate = new \app\common\validate\mk\Sms();
        $validate->setRule($validate->loginRule);
        if (!$validate->check(input())) {
            return apiError($validate->getError());
        }
        try {
            $res = UsersService::sms_login(input());
            return apiSuccess($res);
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }



    public function userUpdate()
    {
        $data = array();
        if (input('name')) $data["name"] = base64_encode(input('name')); //微信昵称
        if (input('avatar')) $data["avatar"] = input('avatar'); //头像

        //获取当前用户信息
        $api_token = Request::instance()->header('authorization');
        if (empty($api_token)) {
            return apiError("请授权登录", -100);
        }
        $user = Db::table('sms_mk_users')
            //            ->where('id',$this->userId)
            ->where('api_token', '=', $api_token)
            ->find();
        if (empty($user)) {
            return apiError("该用户不存在", 403);
        }

        $update = Db::table('sms_mk_users')->where('id', $user['id'])->update($data);
        if (!empty($update)) {
            return apiSuccess();
        }
        return apiError();
    }

    /**
     *微信小程序登录
     */
    public function wx_mp_login()
    {

        $url = "https://api.weixin.qq.com/sns/jscode2session";
        // 参数
        $params['appid'] = config('weChat')['appid'];
        $params['secret'] = config('weChat')['AppSecret'];
        $params['js_code'] = input('code');

        $arr = httpPost($url, $params);
        $arr = json_decode($arr, true);
        //模拟登陆
        //unset($arr['errcode']);$arr['wx_openid'] = 1111111;
        if (isset($arr['errcode']) && !empty($arr['errcode'])) {
            return apiError($arr['errcode'] . $arr['errmsg'], 403);
        }

        $api_token = 'wx_' . $arr['openid'] . rand(100000, 999999);
        $api_token = md5($api_token); //api唯一标识

        $userInfo = Db::table('sms_users')->where('wx_openid', $arr['openid'])->find();
        if (!empty($userInfo)) {
            //登录
            Db::table('sms_users')
                ->where('id', $userInfo['id'])
                //->where('wx_openid',$arr['wx_openid'])
                ->update([
                    'api_token' => $api_token,
                    'update_time' => time(),
                ]);
            $res = [/*'wx_openid'=>$arr['wx_openid'],*/'userId' => $userInfo['id'], 'api_token' => $api_token];
            return apiSuccess($res, '微信登录成功');
        } else {
            //注册
            $inserId = Db::table('sms_users')->insertGetId([
                'wx_openid' => $arr['wx_openid'],
                'api_token' => $api_token,
                'create_time' => time(),
            ]);
            $res = [/*'wx_openid'=>$arr['wx_openid'],*/'userId' => $inserId, 'api_token' => $api_token];
            return apiSuccess($res, '微信注册成功');
        }
    }
}
